package com.example.xiefeihong.chatroom.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by xiefeihong on 17-9-30.
 */

public class HttpUtils {

    private static final String baseUrl = "http://192.168.1.158:8080/";

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private static final String TAG = "HttpUtils";

    private static Context context = AppUtils.getContext();

    private static OkHttpClient client = new OkHttpClient.Builder()
           // .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(1000000, TimeUnit.SECONDS)
            .build();

    public static boolean isNetworkConnected() {
        if (context != null) {
            ConnectivityManager connectvivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectvivityManager.getActiveNetworkInfo();
            if (networkInfo != null) {
                return networkInfo.isAvailable();
            }
        }
        return false;
    }

    public static void toastNetworkNotConnected(){
        Toast.makeText(context, "network is nuavailabel", Toast.LENGTH_SHORT).show();
    }

    public static String get(String url) {
        if(!isNetworkConnected()){
            toastNetworkNotConnected();
            return "";
        }
        Request request = new Request.Builder()
                .url(baseUrl + url)
                .build();
        String responseText = null;
        try {
            Response response = client.newCall(request).execute();
            responseText = response.body().string();
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
        Log.d(TAG, baseUrl + url + " ： " + responseText);
        return responseText;
    }

    public static String post(String url, String json) {
        if(!isNetworkConnected()){
            toastNetworkNotConnected();
            return "";
        }
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(baseUrl + url)
                .post(body)
                .build();
        String responseText = null;
        try {
            Response response = client.newCall(request).execute();
            responseText = response.body().string();
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
        Log.d(TAG, baseUrl + url + " ： " + json + " : " + responseText);
        return responseText;
    }

}
